package com.linzm.leetcode.primary.exercises3_20230122;

/**
 * @Author zimingl
 * @Date 2023/1/27 22:56
 * @Description: 连续子数组的最大和
 */
public class Demo38 {
    /**
     * 输入: nums = [-2,1,-3,4,-1,2,1,-5,4]
     * 输出: 6
     * 解释: 连续子数组 [4,-1,2,1] 的和最大，为 6。
     */
    public static void main(String[] args) {
        Demo38 demo38 = new Demo38();
        int[] nums = {-2, 4, -3, 4, -1, 2, 1, -5, 4};
        int maxSubArray = demo38.maxSubArray(nums);
        System.out.println(maxSubArray);
    }

    private int maxSubArray(int[] nums) {
        int pre = 0, tmp = 0, maxAns = nums[0];
        for (int x : nums) {
            tmp = pre + x;
            pre = Math.max(tmp, x);
            maxAns = Math.max(maxAns, pre);
        }
        return maxAns;
    }
}
